﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZhwangTool
{
    /// <summary>
    /// FindFileUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class FindFileUserControl : UserControl
    {
        
        public FindFileUserControl()
        {
            InitializeComponent();
        }

        

   
        private void ComBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        List<string> nameList = new List<string>();

        List<string> paths = new List<string>();

        ObservableCollection<MyFileInfo> sourceList_dataGrid1 = new ObservableCollection<MyFileInfo>();

        ObservableCollection<MyFileInfo> sourceList_dataGrid2 = new ObservableCollection<MyFileInfo>();



        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void ListFileButton_Click(object sender, RoutedEventArgs e)
        {
            //FileInfo fileInfo = new FileInfo("t");
            //fileInfo.Extension

            sourceList_dataGrid1.Clear();

            string givenPath = textBox1.Text;

            string path = textBox1.Text;

            if (System.IO.Directory.Exists(path) == false)
            {
                return;
            }

            #region 控制文件类型

            string p = "*";

            List<string> nameListInCurPath = new List<string>();

            nameListInCurPath =Tools.Getfiles(path, p, checkBox1.IsChecked);

            switch (comBox1.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".dwg")).ToList<string>();
                    break;
                case 2:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".xls") || x.EndsWith(".xlsx")).ToList<string>();
                    break;
                case 3:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".ppt") || x.EndsWith(".pptx")).ToList<string>();
                    break;
                case 4:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx")).ToList<string>();
                    break;
                case 5:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".pdf")).ToList<string>();
                    break;
                case 6:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".rar") || x.EndsWith(".zip") || x.EndsWith(".7z")).ToList<string>();
                    break;
                case 7:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx") || x.EndsWith(".dwg") || x.EndsWith(".ppt") ||
                     x.EndsWith(".pptx") || x.EndsWith(".xls") || x.EndsWith(".xlsx") || x.EndsWith("*.pdf")).ToList<string>();
                    break;
                case 8:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".jpg") || x.EndsWith(".JPG") || x.EndsWith(".BMP") || x.EndsWith(".bmp") || x.EndsWith(".png") || x.EndsWith(".PNG") ||
                    x.EndsWith(".jpeg") || x.EndsWith(".JPEG")).ToList<string>();
                    break;
                case 9:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".bak")).ToList<string>();
                    break;
                case 10:
                    //nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(textBox2.Text.Trim())).ToList<string>();

                    string[] tagsTmp = textBox2.Text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (tagsTmp.Length>0)
                    {
                        nameListInCurPath = nameListInCurPath.Where(x => tagsTmp.Any(tag => x.EndsWith(tag))).ToList<string>();
                    }
                    break;
                    
                default:
                    break;
            }
          
            #endregion

            
            #region  --处理文件名中包含关键字的情况

            //将包含给定字符串的文件名添加到给定的结合中

            //List<string> tmp_names = new List<string>();

            //string[] tagS = containTag.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            //List<string> containTagFileNames = new List<string>();

            //foreach (string tmpFileName in nameListInCurPath)
            //{

            //    bool allWordsFound = true; // 假设所有单词都找到了，然后逐个检查

            //    foreach (string word in tagS)
            //    {
            //        //判断是否是可以包容的词

            //        string[] tagSTmp = word.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            //        //包含可选字符情况

            //        if (tagSTmp.Length > 0)
            //        {
            //            bool tmp = false;

            //            foreach (var item in tagSTmp)
            //            {

            //                if (System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(item))
            //                {
            //                    tmp = true; // 如果发现某个单词不在字符串中，标记为未找到 

            //                    break; // 跳出循环，因为已经知道不是所有单词都找到了
            //                }

            //            }

            //            if (!tmp)
            //            {
            //                allWordsFound = false;
            //                break;
            //            }
            //        }
            //        else
            //        {
            //            if (!System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(word))
            //            {
            //                allWordsFound = false; // 如果发现某个单词不在字符串中，标记为未找到
            //                                       //Console.WriteLine($"The word '{word}' was not found in the string.");
            //                break; // 跳出循环，因为已经知道不是所有单词都找到了
            //            }

            //        }
                    
            //    }
      
            //    if (allWordsFound)
            //    {
            //        containTagFileNames.Add(tmpFileName);
            //    }

            //}

            #endregion




            //SelectedIndex==0 表示不控制时间

            if (comBoxTime.SelectedIndex == 0)
            {
                sourceList_dataGrid1.Clear();
                
                foreach (var item in nameListInCurPath)
                {

                    try
                    {
                        MyFileInfo fileInfo = new MyFileInfo(item, givenPath);
                        sourceList_dataGrid1.Add(fileInfo);
                    }
                    catch (Exception)
                    {
                        continue;
                        //throw;
                    }

                }

                dataGrid1.ItemsSource = sourceList_dataGrid1.OrderBy(x => x.Name);

            }

            //根据前面判断，此处需要处理控制时间范围

            #region --接下来处理给定日期范围内的文件

            if (startTimeDate.SelectedDate.Value == null || endTimeDate.SelectedDate.Value == null)
            {
                MessageBox.Show("未选定有效的起始日期和截止日期，跳过对时间复合型检查");
                return;
            }
            #region 调整时间范围顺序，兼容起始日期晚于截止日期


            DateTime timeA = startTimeDate.SelectedDate.Value.Date;
            DateTime timeB = endTimeDate.SelectedDate.Value.Date;

            DateTime startTime = System.DateTime.Today;
            DateTime endTime = System.DateTime.Today;

            if (timeA >= timeB)
            {
                startTime = timeB;
                endTime = timeA;
            }
            else
            {
                startTime = timeA;
                endTime = timeB;
            }

            #endregion


            switch (comBoxTime.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    nameListInCurPath = nameListInCurPath.Where(x => System.IO.File.GetLastWriteTime(x).Date >= startTime &&
                                                                         System.IO.File.GetLastWriteTime(x).Date <= endTime).ToList<string>();
                    break;

                case 2:
                    nameListInCurPath = nameListInCurPath.Where(x => System.IO.File.GetCreationTime(x).Date >= startTime &&
                                                                         System.IO.File.GetCreationTime(x).Date <= endTime).ToList<string>();
                    break;

                case 3:
                    nameListInCurPath = nameListInCurPath.Where(x => System.IO.File.GetLastAccessTime(x).Date >= startTime &&
                                                                         System.IO.File.GetLastAccessTime(x).Date <= endTime).ToList<string>();
                    break;

                default:
                    break;
            }


            sourceList_dataGrid1.Clear();

            foreach (var item in nameListInCurPath)
            {
                try
                {


                    MyFileInfo fileInfo = new MyFileInfo(item, givenPath);

                    sourceList_dataGrid1.Add(fileInfo);
                }
                catch (Exception)
                {
                    MessageBox.Show(item.Length.ToString());
                    continue;
                    //throw;
                }
                
            }

            dataGrid1.ItemsSource = sourceList_dataGrid1.OrderBy(x => x.LastWriteTime);

            #endregion
            
        }

        public static List<string> Getfilesa(string filepath, string pattern,bool? childFolder)
        {
            string p = pattern;

            List<string> f_name_list = new List<string>();

            if (childFolder==true)
            {
                f_name_list = System.IO.Directory.GetFiles(filepath, p, System.IO.SearchOption.AllDirectories).ToList<string>();
            }
            else
            {
                f_name_list = System.IO.Directory.GetFiles(filepath, p, System.IO.SearchOption.TopDirectoryOnly).ToList<string>();
            }
            return f_name_list;
        }
        

        private void ComBoxTime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (comBoxTime.SelectedIndex==0)
            //{
            //    startTimeDate.IsEnabled = false;
            //    endTimeDate.IsEnabled = false;
            //}
            //else
            //{
            //    startTimeDate.IsEnabled = true;
            //    endTimeDate.IsEnabled = true;

            //}
        }

        //private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        //{

        //    FlowDocument fdoc = richTextBox.Document;

        //    Paragraph paragraph = new Paragraph();
            
        //    string filePath = listBox1.SelectedItem.ToString();

        //    richTextBox.Document.Blocks.Clear();

        //    if (System.IO.File.Exists(filePath))
        //    {
        //        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

        //        Run run1 = new Run("文件修改时间" + "\r\n" + fileInfo.LastAccessTime.Date.ToLocalTime()+ "\r\n");
                
        //        run1.Foreground = Brushes.Black;

        //        paragraph.Inlines.Add(run1);

        //        Run run2 = new Run("文件创建时间" + "\r\n" + fileInfo.CreationTime.Date + "\r\n");

        //        run2.Foreground = Brushes.Black;

        //        paragraph.Inlines.Add(run2);

        //        Run run3 = new Run("文件大小(Mb)" + "\r\n" + (fileInfo.Length/1024.0/1024.0).ToString("F3") + "\r\n");

        //        run3.Foreground = Brushes.Black;

        //        paragraph.Inlines.Add(run3);





        //        richTextBox.Document.Blocks.Add(paragraph);

        //        richTextBox.ScrollToEnd();
                
        //    }



        //}

        //private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{

        //    MyFileInfo fi = dataGrid1.SelectedItem as MyFileInfo;


        //    if (fi == null)
        //    {
        //        return;
        //    }

        //    //下边写用richtextbox的情况

        //    FlowDocument fdoc = richTextBox.Document;

        //    //fdoc.Blocks.Clear();

        //    Paragraph paragraph = new Paragraph();

        //    Run run1 = new Run("File:" + fi.Name + "\r\n");

        //    run1.Foreground = Brushes.Black;

        //    Run run2 = new Run("最后写入时间:" + "\r\n");

        //    run2.Foreground = Brushes.Black;

        //    run2.FontWeight = FontWeights.Bold;

        //    Run run3 = new Run(fi.LastWriteTime.ToString()+ "\r\n");

        //    run3.Foreground = Brushes.Red;

        //    run3.FontWeight = FontWeights.Bold;

        //    Run run4 = new Run("文件创建时间:" + "\r\n");

        //    run4.Foreground = Brushes.Black;
        //    run4.FontWeight = FontWeights.Bold;

        //    Run run5 = new Run(fi.CreationTime.ToString() + "\r\n");

        //    run5.Foreground = Brushes.Red;
        //    run5.FontWeight = FontWeights.Bold;

        //    paragraph.Inlines.Add(run1);

        //    paragraph.Inlines.Add(run2);

        //    paragraph.Inlines.Add(run3);

        //    paragraph.Inlines.Add(run4);

        //    paragraph.Inlines.Add(run5);

        //    richTextBox.Document.Blocks.Add(paragraph);

        //    richTextBox.ScrollToEnd();

        //    scrollViewer1.ScrollToBottom();
            
        //}

        private void DataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            FileInfo fileInfo = e.Row.Item as FileInfo;

           
            

            //MyFileInfo myFileInfo = e.Row.Item as MyFileInfo;
            //if (myFileInfo.Tag % 2 == 0)
            //{
            //    e.Row.Background = new SolidColorBrush(Colors.White);
            //}
            //else
            //{

            //    e.Row.Background = new SolidColorBrush(Colors.PaleTurquoise);

            //}

        }

        private void DataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            MyFileInfo myFileInfo = dataGrid1.SelectedItem as MyFileInfo;

            if (myFileInfo != null)
            {
                string file_Name = myFileInfo.Name;

                string tmp_path = System.IO.Path.GetDirectoryName(file_Name);

                System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);
            }

        }


        private void RunCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("woyunxingle");
        }

        private void ContainTag_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ListFileButton_Click_1(sender, e);




                // 回车键被按下，执行你想要的操作
                //MessageBox.Show("回车键被按下");
                // 如果你想要阻止进一步的处理，可以设置e.Handled = true;
                // e.Handled = true;
            }
        }

        private void ListFileButton_Click_1(object sender, RoutedEventArgs e)
        {
            ObservableCollection<MyFileInfo> myFileInfos = new ObservableCollection<MyFileInfo>();

            
            if (dataGrid1.ItemsSource==null)
            {
                return;
            }

            //将包含给定字符串的文件名添加到给定的结合中

            List<string> tmp_names = new List<string>();

            string[] tagS = containTag.Text.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);

            List<string> containTagFileNames = new List<string>();
            
            foreach (var myFileInfoitem in sourceList_dataGrid1)
            {
                try
                {

                    MyFileInfo fileInfo = myFileInfoitem as MyFileInfo;

                    if (fileInfo==null)
                    {
                        return;
                    }

                    string tmpFileName = fileInfo.Name;

                    bool allWordsFound = true; // 假设所有单词都找到了，然后逐个检查

                    foreach (string word in tagS)
                    {
                        //判断是否是可以包容的词

                        string[] tagSTmp = word.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        //包含可选字符情况

                        if (tagSTmp.Length > 0)
                        {
                            bool tmp = false;

                            foreach (var item in tagSTmp)
                            {

                                if (System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(item))
                                {
                                    tmp = true; // 如果发现某个单词不在字符串中，标记为未找到 

                                    break; // 跳出循环，因为已经知道不是所有单词都找到了
                                }

                            }

                            if (!tmp)
                            {
                                allWordsFound = false;
                                break;
                            }
                        }
                        else
                        {
                            if (!System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(word))
                            {
                                allWordsFound = false; // 如果发现某个单词不在字符串中，标记为未找到
                                                       //Console.WriteLine($"The word '{word}' was not found in the string.");
                                break; // 跳出循环，因为已经知道不是所有单词都找到了
                            }

                        }

                    }

                    if (allWordsFound)
                    {
                        fileInfo.ToShow = true;

                        myFileInfos.Add(fileInfo);


                    }
                    else
                    {
                        fileInfo.ToShow = false;
                    }
                    
                }
                catch (Exception)
                {
       
                }

            }


            dataGrid1.ItemsSource = myFileInfos.OrderBy(x => x.LastWriteTime);



        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ObservableCollection<MyFileInfo> myFileInfos = new ObservableCollection<MyFileInfo>();


            if (dataGrid1.ItemsSource == null)
            {
                return;
            }

            //将包含给定字符串的文件名添加到给定的结合中

            List<string> tmp_names = new List<string>();

            string[] tagS = containTag.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            List<string> containTagFileNames = new List<string>();

            foreach (var myFileInfoitem in dataGrid1.ItemsSource)
            {
                try
                {

                    MyFileInfo fileInfo = myFileInfoitem as MyFileInfo;

                    if (fileInfo == null)
                    {
                        return;
                    }

                    string tmpFileName = fileInfo.Name;

                    bool allWordsFound = true; // 假设所有单词都找到了，然后逐个检查

                    foreach (string word in tagS)
                    {
                        //判断是否是可以包容的词

                        string[] tagSTmp = word.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        //包含可选字符情况

                        if (tagSTmp.Length > 0)
                        {
                            bool tmp = false;

                            foreach (var item in tagSTmp)
                            {

                                if (System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(item))
                                {
                                    tmp = true; // 如果发现某个单词不在字符串中，标记为未找到 

                                    break; // 跳出循环，因为已经知道不是所有单词都找到了
                                }

                            }

                            if (!tmp)
                            {
                                allWordsFound = false;
                                break;
                            }
                        }
                        else
                        {
                            if (!System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(word))
                            {
                                allWordsFound = false; // 如果发现某个单词不在字符串中，标记为未找到
                                                       //Console.WriteLine($"The word '{word}' was not found in the string.");
                                break; // 跳出循环，因为已经知道不是所有单词都找到了
                            }

                        }

                    }

                    if (allWordsFound)
                    {
                        fileInfo.ToShow = true;

                        myFileInfos.Add(fileInfo);


                    }
                    else
                    {
                        fileInfo.ToShow = false;
                    }

                }
                catch (Exception)
                {

                }

            }
        }
    }
}
